package com.gaoxizhe.ccc.config;/**
 * @author : Mr.Gao
 * @date :   2019/9/25 22:02
 */

import com.gaoxizhe.ccc.base.CurrentUser;
import com.gaoxizhe.ccc.model.login.User;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

/**
 * @ClassName CurrentUserMethodArgumentResolver
 * @Author Mr.Gao
 * @Date 2019/9/25 22:02
 * @Description TODO |  自定义参数解析器（解析user）
 */
public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter){
        return parameter.getParameterType().isAssignableFrom(User.class) //判断是否能转换成User类型
                && parameter.hasParameterAnnotation(CurrentUser.class); //是否有CurrentUser注解
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        User user = (User) webRequest.getAttribute("user", RequestAttributes.SCOPE_REQUEST);
        if (user != null) {
            return user;
        }
        throw new MissingServletRequestPartException("user");
    }
}
